package works_collection

import (
	"fmt"
	"jihe.common/protos/base_server/proto"
	"jihe.common/tool"
	"time"
)

func (s *Tx) Create(in *proto.BaseWorksCollection) (out *proto.BaseWorksCollection, err error) {
	out = new(proto.BaseWorksCollection)
	in.Id = fmt.Sprintf("%d", tool.GetSnowflakeId())
	sqlStr := fmt.Sprintf("INSERT INTO %s (id, name, uid, cover)VALUES($1,$2,$3,$4)", s.Name)
	_, err = s.Db.Exec(sqlStr, in.Id, in.Name, in.Uid, in.Cover)
	if err != nil {
		return
	}
	out = in
	return
}

func (s *Tx) Update(in *proto.BaseWorksCollection) (err error) {
	sqlStr := fmt.Sprintf("UPDATE %s SET name = $1, cover = $2, updated_at = $3 WHERE id = $4", s.Name)
	_, err = s.Db.Exec(sqlStr, in.Name, in.Cover, time.Now().Format("2006-01-02 15:04:05"), in.Id)
	if err != nil {
		return
	}
	return
}

func (s *Tx) Delete(id string) (err error) {
	sqlStr := fmt.Sprintf("DELETE FROM %s WHERE id = $1", s.Name)
	_, err = s.Db.Exec(sqlStr, id)
	if err != nil {
		return
	}
	return
}

func (s *Model) DetailById(id string) (ret *proto.BaseWorksCollection, err error) {
	ret = new(proto.BaseWorksCollection)
	sqlStr := fmt.Sprintf("select id, name, uid, cover, created_at, updated_at from %s where id = $1", s.Name)
	var (
		createdAt *time.Time
		updatedAt *time.Time
	)
	err = s.Db.QueryRow(sqlStr, id).Scan(&ret.Id, &ret.Name, &ret.Uid, &ret.Cover, &createdAt, &updatedAt)
	if err != nil {
		return
	}
	ret.CreatedAt = createdAt.Format("2006-01-02 15:04:05")
	ret.UpdatedAt = updatedAt.Format("2006-01-02 15:04:05")
	return
}

func (s *Model) GetListByUid(uid string) (ret []*proto.BaseWorksCollection, err error) {
	sqlStr := fmt.Sprintf("select id, name, uid, cover, created_at, updated_at from %s where uid = $1 order by created_at desc limit 100", s.Name)
	rows, err := s.Db.Query(sqlStr, uid)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		item := &proto.BaseWorksCollection{}
		var (
			createdAt *time.Time
			updatedAt *time.Time
		)
		err = rows.Scan(&item.Id, &item.Name, &item.Uid, &item.Cover, &createdAt, &updatedAt)
		if err != nil {
			return
		}
		item.CreatedAt = createdAt.Format("2006-01-02 15:04:05")
		item.UpdatedAt = updatedAt.Format("2006-01-02 15:04:05")
		ret = append(ret, item)
	}
	return
}
